<template>
    <view class="page" id="test">
      <view class="cate_content">
        <scroll-view scroll-y="true" :scroll-top="leftScrollTop" class="left"
                     :style="{'height':scrollHeight + 'px','top':stickyTop + 'px'}">
          <view class="">
            <view class="menu_name" :id="'menu_name' + index" style="position: relative;"
                  :class="{'menu_name_active':currentIndex == index}" v-for="(item,index) in productList"
                  @click="onChangeCate(item,index)" :key="index">
              <text class="goods-group-border" v-if="currentIndex == index"></text>
              <text class="name">{{item.name}}</text>
            </view>
          </view>
        </scroll-view>
        <view class="right">
          <view class="item" v-for="(item,index) in productList" :key="index">
            <view class="title ">
              <view class="title-top-containers">
                <view>{{item.name}}</view>
                <view class="color-385CD6"  @click="inspectionLevelAisles(item.aisleList)">检测{{item.name}}</view>
              </view>
            </view>
            <view class="content">
              <view class="product_item"
                    :class="motorStatusMap.get(String(aisle.laneNumber))===1?
                    'color-normal':motorStatusMap.get(String(aisle.laneNumber))===2?
                    'color-fault':motorStatusMap.get(String(aisle.laneNumber))===3?'color-blue':'color-not-detected'"
                    v-for="(aisle,aisleIndex) in item.aisleList" :key="aisleIndex">
                <view class="aisle">{{ aisle.laneNumber }}</view>
                <view class="status-normal" v-if="motorStatusMap.get(String(aisle.laneNumber))===1">正常</view>
                <view class="status-exception" v-else-if="motorStatusMap.get(String(aisle.laneNumber))===2">电机故障</view>
                <view v-else-if="motorStatusMap.get(String(aisle.laneNumber))===3" class="u-flex">
                  <u-loading-icon mode="circle" inactiveColor="#6072ff" inactive-color="#FFF" size="24rpx"></u-loading-icon>
                  <view class="status-testing">检测中</view>
                </view>
                  <u-button  @click="singleAisleInspection(aisle)" :customStyle="{height: '50rpx', borderRadius: '40rpx'}" text="检测"></u-button>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 底部区域 -->
      <view class="foot ">
        <view class="inner">
<!--          <u-button @click="goWapBindingDevice" :customStyle="{width: '180rpx', height: '70rpx', borderRadius: '40rpx',color:'#385CD6'}" text="绑定设备"></u-button>-->
          <u-button @click="resetState" :customStyle="{width: '180rpx', height: '70rpx', borderRadius: '40rpx',color:'#385CD6'}" text="重置状态"></u-button>
          <u-button @click="checkAll" :customStyle="{width: '180rpx', height: '70rpx', borderRadius: '40rpx',background:'rgb(96, 114, 255)',color:'#FFFFFF'}" text="全部检测"></u-button>
        </view>
      </view>
    </view>
</template>

<script>
import { eventBus } from '@/main.js'
export default {
  name: "channelManagement",
  data() {
    return {
      deviceNo:'',
      windowHeight: uni.getSystemInfoSync().windowHeight, //窗口高度
      scrollHeight: uni.getSystemInfoSync().windowHeight, //滚动高度
      backgroundColor: "rgba(255,255,255,0)",
      allAreaHeight: 0, //顶部的总区域高度
      topList: [], //
      currentIndex: 0,
      leftScrollTop: 0,
      rightItemHeight: 0,
      stickyTop: 0, //吸顶的距离
      productList: [],
      isClick: false,
      aisleList:[],
      motorStatusMap:new Map,
      numberOfFailuresMap:new Map,
      isBluetooth:false,
      storageKeyEnum : this.$storageKeyEnum,
      connectionStatus: -1,
    }
  },
  onLoad(options) {
    // #ifdef H5
    if (options.token) {
      this.$login.getH5Login(options.token);
    }
    // #endif
    if (this.$u.test.isEmpty(options.deviceNo) && this.$u.test.isEmpty(options.isBluetooth)) {
        return
    }else{
      let tent = this;
      let setT;
      try {
        // #ifndef  MP-TOUTIAO
        setT = setTimeout(() => {
          tent.init(options.deviceNo);
        },1000)
        // #endif
        // #ifdef  MP-TOUTIAO
        this.$nextTick(() => {
          tent.init(options.deviceNo);
        },1000)
        // #endif
      }catch (e) {
        clearTimeout(setT);
        console.error(e.toString())
      }
    }
    this.deviceNo=options.deviceNo;
    if(options.isBluetooth == 'true'){
      this.isBluetooth = options.isBluetooth;
      this.$bluetooth.initBluetooth(this.deviceNo,this.isBluetooth);
    }
    this.findAisleByDeviceNo();
    if (uni.getStorageSync(this.storageKeyEnum.test_results_list+this.deviceNo)){
        let list = JSON.parse(uni.getStorageSync(this.storageKeyEnum.test_results_list+this.deviceNo))
        list.forEach((item)=>{
          this.motorStatusMap.set(item.k,item.v);
        })
    }
  },
  // onReady() {
  //   this.$nextTick(() => {
  //     this.scrollHeight = this.windowHeight - this.allAreaHeight  - 130;
  //     this.getTop();
  //   })
  // },
  mounted(){
    this.watchSocket();
  },
  created() {
    // 监听事件
    eventBus.$on('connectionStatus', this.handleEventConnectionStatus)
    eventBus.$on('webSocketReconnect', this.watchSocket)
  },
  methods: {
    watchSocket() {
      this.$socket.getMessage(opt => {
        console.info("channel-management消息接收：", opt.data);
        const result = JSON.parse(opt.data)
        if (!uni.$u.test.isEmpty(result.hierarchy) && !uni.$u.test.isEmpty(result.freightLane)){
            this.motorStatusMap.set(this.encodeHierarchyFreightLane(result.hierarchy,result.freightLane),result.motorStatus);
            let list = [];
            this.motorStatusMap.forEach((v,k,map)=>{
              list.push({'v':v,'k':k})
            })
            uni.setStorageSync(this.storageKeyEnum.test_results_list+this.deviceNo,JSON.stringify(list));
            this.$forceUpdate();
        }
      })
    },
    handleEventConnectionStatus(connectionStatus) {
      console.log('connectionStatus变化',connectionStatus)
      this.connectionStatus = connectionStatus;
    },
    encodeHierarchyFreightLane(hierarchy, freightLane) {
      // 将输入的数字转换为字符串
      let hierarchyStr = String(hierarchy);
      let freightLaneStr = String(freightLane);

      // 仅对freightLane进行补零操作，确保至少有两位
      freightLaneStr = freightLaneStr.padStart(2, '0');
      // 拼接最终的结果字符串
      return hierarchyStr + freightLaneStr;
    },
    init(deviceNo) {
      if (this.$u.test.isEmpty(deviceNo)) {
        this.$helpers.toast("设备号为空");
        return
      }
      this.deviceNo=deviceNo;
      if (this.isBluetooth == 'true') {
         this.$bluetooth.startBLEConnectionStateListening(this.deviceNo); // 页面加载时，启动蓝牙连接状态的监听
      }
      this.findAisleByDeviceNo();
      if (uni.getStorageSync(this.storageKeyEnum.test_results_list+this.deviceNo)){
        let list = JSON.parse(uni.getStorageSync(this.storageKeyEnum.test_results_list+this.deviceNo))
        list.forEach((item)=>{
          this.motorStatusMap.set(item.k,item.v);
        })
      }
    },
    //检测所有货道
    checkAll(){
      if (this.isBluetooth == 'true') {
        if (this.connectionStatus == 2){
          // 蓝牙可用时才执行后续逻辑
          this.aisleList=[];
          this.productList.forEach(item=>{
            this.aisleList.push(...item.aisleList);
          })
          this.findSendDetectionByDeviceNo();
        } else if (this.connectionStatus == 1) {
          this.$helpers.toast('正在连接蓝牙设备中...');
        } else if (this.connectionStatus == 3) {
          this.$bluetooth.disconnectPrompt();
        }
      }else {
        this.aisleList=[];
        this.productList.forEach(item=>{
          this.aisleList.push(...item.aisleList);
        })
        this.findSendDetectionByDeviceNo();
      }
    },
    //检测整层货道
    inspectionLevelAisles(aisleList){
      if (this.isBluetooth == 'true') {
          if (this.connectionStatus == 2){
            this.aisleList=aisleList;
            this.findSendDetectionByDeviceNo();
          } else if (this.connectionStatus == 1) {
            this.$helpers.toast('正在连接蓝牙设备中...');
          } else if (this.connectionStatus == 3) {
            this.$bluetooth.disconnectPrompt();
          }
      }else {
        this.aisleList = aisleList;
        this.findSendDetectionByDeviceNo();
      }
    },
    //单货道检测
    singleAisleInspection(aisle) {
      if (this.isBluetooth == 'true') {
          if (this.connectionStatus == 2){
            // 蓝牙可用时才执行后续逻辑
            this.aisleList = [];
            this.aisleList.push(aisle);
            this.findSendDetectionByDeviceNo();
          } else if (this.connectionStatus == 1) {
            this.$helpers.toast('正在连接蓝牙设备中...');
          } else if (this.connectionStatus == 3) {
            this.$bluetooth.disconnectPrompt();
          }
      }else{
        this.aisleList = [];
        this.aisleList.push(aisle);
        this.findSendDetectionByDeviceNo();
      }
    },
    //获取货道信息
    findAisleByDeviceNo(){
      let param = {
        deviceNo: this.deviceNo,
      }
      this.$api('device.findAisleByDeviceNo', param).then(res => {
        if (res.status == 0) {
            this.productList=res.data;
            this.$nextTick(() => {
              this.scrollHeight = this.windowHeight - this.allAreaHeight  - 87;
              this.getTop();
            })
        }else{
          this.$helpers.toast(res.msg);
        }
      }).catch(err => {
        uni.hideLoading();
      })
    },
    //发送货道检测
    findSendDetectionByDeviceNo(){
      let param = {
        deviceNo: this.deviceNo,
        aisleList:this.aisleList,
        socketId: getApp().globalData.socketId,
      }
      console.info("电机检测socketId：", getApp().globalData.socketId);
      console.log("电机检测socketId：", getApp().globalData.socketId)
      this.$api('device.findSendDetectionByDeviceNo', param).then(res => {
        if (res.status == 0) {
            this.aisleList.forEach(item=>{
              this.motorStatusMap.set(this.encodeHierarchyFreightLane(item.hierarchy,item.freightLane),3);
            })
            this.$forceUpdate();
        }else {
          this.$helpers.toast(res.msg);
        }
      }).catch(err => {
        this.$helpers.toast('发送检测失败');
      })
    },
    resetState(){
      uni.removeStorage(this.storageKeyEnum.test_results_list+this.deviceNo)
      this.motorStatusMap=new Map;
    },
    goWapBindingDevice(){

      if (this.$u.test.isEmpty(this.deviceNo)){
        this.$helpers.toast("设备号为空");
        return
      }

      uni.navigateToMiniProgram({
        appId: this.$configPath.shareAppletAppId,
        path: 'pages-device/device-binding/device-binding?deviceNo=' + this.deviceNo,
        envVersion: this.$configPath.envVersion,
        success: res => {
          // 打开成功
          console.log("打开成功", this.deviceNo);
        },
        fail: err => {
          console.log(err);
        }
      });
    },
    /**
     * 获取右边内容距离顶部的距离
     */
    getTop() {
      uni.createSelectorQuery().select('.menu_name').boundingClientRect().exec((rect) => {
        let popupHeight1 = rect[0].height;
        uni.createSelectorQuery().selectAll('.item').boundingClientRect().exec((rect) => {
          let popupHeight2 = rect[0];
          this.rightItemHeight=popupHeight1
          popupHeight2.map((item, index) => {
            this.topList.push({
              top: parseInt(item.top - this.stickyTop),
              bottom: parseInt(item.bottom - this.stickyTop),
            });
          })
        });
      });
    },
    /**
     * 点击货道
     */
    onChangeCate(item, index) {
      if (this.currentIndex == index) {
        return;
      }
      this.isClick = true;
      this.currentIndex = index;
      this.leftScrollTop = this.rightItemHeight * index;
      uni.pageScrollTo({
        scrollTop: this.topList[index].top,
      })
      setTimeout(() => {
        this.isClick = false;
      }, 600)
    },
  },

  onPageScroll(e) {
    let opacity = (e.scrollTop / 100).toFixed(2);
    this.backgroundColor = "rgba(255,255,255," + (opacity >= 1 ? 1 : opacity) + ")";
    if (!this.isClick) {
      let scrollTop = parseInt(e.scrollTop);
      for (var i = 0; i < this.topList.length; i++) {
        if (scrollTop >= this.topList[i].top && scrollTop <= this.topList[i].bottom) {
          this.currentIndex = i;
          this.leftScrollTop = this.rightItemHeight * i;
          break;
        }
      }
    }

  },

}
</script>
<style>
page {
  height: auto;
}
</style>
<style lang="scss" scoped>
.page{
  background-color: #FFFFFF !important;
}
view {
  box-sizing: border-box;
}
  .color-385CD6{
    color: #385CD6 !important;
  }
.state_height {
  height: var(--status-bar-height);
}

.page {
  padding-bottom: calc(constant(safe-area-inset-bottom) + 100rpx);
  padding-bottom: calc(env(safe-area-inset-bottom) + 100rpx);
}
.title-top-containers{
  display: flex;
  justify-content: space-between;
}
.nav_bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background: rgba(0, 0, 0, 0);
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  .nav_bar_inner {
    display: flex;
    padding: 0 20rpx;
    align-items: center;
    justify-content: space-between;
  }
}

.top_area {
  height: 380rpx;
  background-color: #fff;
  background-image: url('https://cdn.uviewui.com/uview/swiper/swiper1.png');
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

.advert_area {
  height: 200rpx;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;

  .img_box {
    width: 94%;
  }
}

.tabs {
  position: sticky;
  top: 0;
  height: 100rpx;
  background: #fff;
  box-shadow: 0 3px 10px -4px rgba(0, 0, 0, 0.2);
  z-index: 999;
}

.swiper_wrap {}

.cate_content {
  /* 	position: sticky;
  top: 100rpx; */
  display: flex;
  flex-direction: row;

  .left {
    position: sticky;
    top: 100rpx;
    width: 150rpx;
    background: #fff;
    // border: 1px solid red;

    .menu_name {
      /* 	position: sticky;
      top: 0; */
      height: 100rpx;
      line-height: 100rpx;
      text-align: center;
      color: #000000E6;

      .name{
        margin-left: 16rpx;
      }
      .goods-group-border {
        border-left: 10rpx solid rgb(96, 114, 255);
        border-radius: 20%;
        color: rgb(96, 114, 255);
      }

    }

    .menu_name_active {

      color: #6072FF;
    }
  }

  .right {
    flex: 1;
    min-height: 100rpx;
    background: #FFF;
    //padding: 0 20rpx;

    .item {
      background: #fff;

      .content{
        padding:0 38rpx;
        display: grid;
        grid-gap: 10rpx;
        grid-template-columns: 1fr 1fr 1fr 1fr;
      }
      .title {
        padding:0 40rpx;
        //position: sticky;
        //top: 100rpx;
        //height: 60rpx;
        line-height: 60rpx;
        background: #fff;
      }
      .color-normal{
        background: rgba(111, 208, 63, 0.2) !important;
      }
      .color-fault{
        background: rgb(255, 229, 229) !important;
      }
      .color-blue{
        background: #D9E9F2 !important;
      }
      .color-not-detected{
        background: rgb(245, 246, 248);
      }
      .product_item {
        padding: 15rpx 10rpx;
        width: 120rpx;
        border-radius: 25rpx;
        //margin-bottom: 20rpx;
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        flex-direction: column;
        justify-content: space-between;
        .aisle{
          color: rgb(34, 34, 34);
          font-size: 32rpx;
        }
        .status-normal{
          color: rgb(82, 196, 26);
          font-size: 24rpx;
        }
        .status-exception{
          color: #FF0000CC;
          font-size: 24rpx;
        }
        .status-testing{
          margin-left: 10rpx;
          color: #0023FF;
          font-size: 24rpx;
        }
      }
    }
  }
}

.foot {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  min-height: 100rpx;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  background: #fff;

  .inner {
    height: 100rpx;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    padding: 0 20rpx;
  }

  .icon_box {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    background: #f5f5f5;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
  }
}

.cart_list {
  padding-bottom: calc(constant(safe-area-inset-bottom) + 100rpx);
  padding-bottom: calc(env(safe-area-inset-bottom) + 100rpx);

  .cart_item {
    height: 120rpx;
    border-bottom: 1px solid #eee;
  }
}
</style>

